package com.white.toolkit

import android.content.Intent
import android.content.pm.PackageManager
import android.graphics.Color
import android.graphics.Matrix
import android.graphics.RectF
import android.os.Bundle
import android.os.Environment
import android.view.View
import android.widget.FrameLayout
import androidx.appcompat.app.AppCompatActivity
import androidx.core.app.ActivityCompat
import androidx.core.content.ContextCompat
import com.aimall.core.define.ImoImageFormat
import com.aimall.core.define.ImoImageOrientation
import com.cnbot.aimolib.AimoEngine
import com.cnbot.aimolib.AvatarBox
import com.cnbot.aimolib.bean.AimoOutlineData
import com.cnbot.aimolib.bean.AimoRawFaceData
import com.cnbot.aimolib.db.AimoFaceDbData
import com.cnbot.aimolib.detect.DetectTask
import com.cnbot.aimolib.detect.DetectType
import com.cnbot.aimolib.recognize.RecognizeTask
import com.qw.soul.permission.SoulPermission
import com.qw.soul.permission.bean.Special
import com.qw.soul.permission.callbcak.SpecialPermissionListener
import com.white.camlib.*
import com.white.loglib.L
import kotlinx.android.synthetic.main.activity_main.*
import java.io.File
import kotlin.properties.Delegates

class MainActivity : AppCompatActivity() {

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        colors = resources.getIntArray(R.array.TrackerRectColors)
        checkPermi()
    }

    private var colors : IntArray by Delegates.notNull()

    private val detectResultCallback = object : DetectTask.Callback{
        override fun onFaceOutlineDetected(facePoints: MutableList<AimoOutlineData>?) {
            facePoints?.let {
                val first = it[0]
                L.e("识别到人脸点位：${first.faceRect.left}, ${first.faceRect.top}, ${first.faceRect.right}, ${first.faceRect.bottom}")
                val list = it.mapIndexed { index, ap ->
                    TrackerDataBundle(ap.faceRect, colors[index % 10], ap.points, Color.GREEN)
                }
                runOnUiThread {
                    trackerView?.postDatas(list)
                }
            }
        }

        override fun onFaceDetectResult(face: AimoRawFaceData?, user: AimoFaceDbData?, vararg transExtra: Any?) {
            user?.let {
                L.e("人脸记录成功：${it._id}")
                it.user_id = "2";
                AimoEngine.getInstance().syncLocaleDb(it)
            }
        }

        override fun onFaceDetectEmpty(vararg transExtra: Any?) {
            trackerView?.postDatas(null)
        }
    }

    private val recognizeCallback = object : RecognizeTask.Callback{
        override fun onFaceOutlineDetected(facePoints: MutableList<AimoOutlineData>?) {
        }

        override fun onRecognized(user: AimoFaceDbData?, vararg transExtra: Any?) {
            L.e("识别完成：用户id=${user?.user_id}")
        }

        override fun onError(msg: String?) {
            L.e("出现错误==>$msg")
        }

    }

    private fun checkPermi() {
        if(ContextCompat.checkSelfPermission(this, android.Manifest.permission.CAMERA)
            != PackageManager.PERMISSION_GRANTED){
            ActivityCompat.requestPermissions(
                this, arrayOf(
                    android.Manifest.permission.CAMERA,
                    android.Manifest.permission.READ_PHONE_STATE,
                    android.Manifest.permission.WRITE_EXTERNAL_STORAGE,
                    android.Manifest.permission.READ_EXTERNAL_STORAGE,
                ), 23
            )
        }else{
            CameraEngine.getInstance().init(this)
        }
    }

    fun click(view: View) {
        when(view){
            start -> {
//                AimoEngine.getInstance().core.execBitmap((resources.getDrawable(R.drawable.women1) as BitmapDrawable).bitmap)
                CameraEngine.getInstance().attachParent2Display(root, frameCallback, textureCallback)
            }
            no_window -> {
//                CameraEngine.getInstance().attachParent2Display(null, frameCallback)
            }
            stop -> {
                CameraEngine.getInstance().detach()
            }
            pic ->{
                startActivity(Intent(this, TakePictureActivity::class.java))
            }
        }
    }

    private val frameCallback = object : CameraKit.FrameCallback{
        override fun onCameraFrame(
            raw: ByteArray?,
            previewWidth: Int,
            previewHeight: Int,
            format: Int
        ) {
            AimoEngine.getInstance().feedDetectData(raw, previewWidth, previewHeight)
        }
    }

    private var trackerView : TrackerView2? = null
    private var portraitBox : AvatarBox? = null

    private val textureCallback = CameraKit.TextureAttachCallback { surface, previewWidth, previewHeight ,textureWid, textureHei->
        runOnUiThread {

            val scale = textureWid * 1.0f / previewWidth
            if(trackerView == null || portraitBox == null){
                trackerView = TrackerView2(this@MainActivity)
                trackerView?.setScale(scale, previewWidth*1.0f/2, previewHeight*1.0f/2)
                //识别框
                portraitBox = AvatarBox(this@MainActivity)
                portraitBox?.setRatio(0.36f, 0.65f)

                root.addView(trackerView, FrameLayout.LayoutParams(textureWid, textureHei))
                root.addView(portraitBox, FrameLayout.LayoutParams(textureWid, textureHei))
            }
            initDetectTask(previewWidth.toFloat(), previewHeight.toFloat(), 0.36f, 0.65f)
//            initRecognizeTask()
        }
    }

    private fun initDetectTask(previewWid : Float, previewHeight : Float, rationWid : Float, ratioHei : Float){

        val finalWid = previewWid * rationWid;
        val finalHei = previewHeight * ratioHei
        val left = (previewWid - finalWid)/2
        val top = (previewHeight - finalHei)/2
        val dst = RectF(left, top, left+finalWid, top + finalHei)

        val file = File(Environment.getExternalStorageDirectory(), "first.jpg")
        val task = DetectTask.Builder()
            .callback(detectResultCallback)
            .detectType(DetectType.STREAM_BYTES)
            .enableSave(false)
            .strictRect(dst)
            .savePath(file.absolutePath)
            .transExtra(12)
            .format(ImoImageFormat.IMO_IMAGE_NV21)
            .orientation(ImoImageOrientation.IMO_IMAGE_UP).build()
        AimoEngine.getInstance().startDetectTask(task)
    }

    private fun initRecognizeTask(){
        val task = RecognizeTask.Builder()
            .callback(recognizeCallback)
            .transExtra(12)
            .format(ImoImageFormat.IMO_IMAGE_NV21)
            .orientation(ImoImageOrientation.IMO_IMAGE_UP).build()
        AimoEngine.getInstance().startRecognizeTask(task)
    }

    override fun onRequestPermissionsResult(
        requestCode: Int,
        permissions: Array<out String>,
        grantResults: IntArray
    ) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults)
        CameraEngine.getInstance().init(this)
        SoulPermission.getInstance().checkAndRequestSpecialPermission(
            Special.DRAW_WINDOW,
            object : SpecialPermissionListener {
                override fun onGranted(permission: Special?) {

                }

                override fun onDenied(permission: Special?) {
                }
            })
    }

    override fun onDestroy() {
        super.onDestroy()
        CameraEngine.getInstance().shutdown()
    }
}